package com.junlong0716.enjoylearning

import android.content.Context
import android.os.Environment
import android.support.v7.app.AppCompatActivity
import com.blankj.utilcode.util.FileUtils
import com.blankj.utilcode.util.ToastUtils
import com.google.gson.Gson
import com.junlong0716.enjoylearning.constant.NetConstant
import com.junlong0716.enjoylearning.entity.CommentEntity
import com.junlong0716.enjoylearning.entity.rxevent.UploadFileProgressEvent
import com.junlong0716.enjoylearning.entity.rxevent.UploadFileSucceedEvent
import com.junlong0716.enjoylearning.net.api.NetApi
import com.junlong0716.module.common.rxbus.RxBus
import com.lzy.okgo.OkGo
import com.lzy.okgo.callback.StringCallback
import com.lzy.okgo.model.Progress
import com.lzy.okgo.model.Response
import org.json.JSONObject
import java.io.File
import kotlin.collections.ArrayList
import kotlin.collections.HashMap
import kotlin.collections.set

/**
 *@author: 巴黎没有摩天轮Li
 *@description:
 *@date: Created in 下午3:04 2018/6/10
 *@modified by:
 */
class CommentPresenter {
    fun requestComment(activity: AppCompatActivity, currentPage: Int, onePageCount: Int, knowledgeId: Int, requestCommentCallback: RequestCommentCallback) {
        val map = HashMap<String, Int>()
//        map["currentPage"] = currentPage
//        map["onePageCount"] = onePageCount
        map["knowledgeId"] = knowledgeId
        map["userId"] = MyApp.instance().userAccount!!.id
        val jsonObj = JSONObject(map)
        OkGo.post<String>(NetConstant.REQUEST_HEADER + NetApi.API_KNOWLEDGE_COMMENT)
                .tag(activity)
                .upJson(jsonObj)
                .execute(object : StringCallback() {
                    override fun onSuccess(response: Response<String>?) {
                        val gson = Gson()
                        val commentEntity = gson.fromJson<CommentEntity>(response!!.body(), CommentEntity::class.java)
                        if (commentEntity.code == "200") {
                            requestCommentCallback.requestCommentSucceed(commentEntity.data.list)
                        }
                    }
                })
    }


    interface RequestCommentCallback {
        fun requestCommentSucceed(commentData: ArrayList<CommentEntity.DataBean.ListBean>)
    }


    fun requestAddComment(activity: AppCompatActivity, userId: Int, knowledgeId: Int, commentContent: String, requestAddCommentCallback: RequestAddCommentCallback) {
        val map = HashMap<String, Any>()
        map["userId"] = userId
        map["commentContent"] = commentContent
        map["knowledgeId"] = knowledgeId
        val jsonObj = JSONObject(map)
        OkGo.post<String>(NetConstant.REQUEST_HEADER + NetApi.API_KNOWLEDGE_ADD_COMMENT)
                .tag(activity)
                .upJson(jsonObj)
                .execute(object : StringCallback() {
                    override fun onSuccess(response: Response<String>?) {
                        val jsonObj = JSONObject(response!!.body())
                        val code = jsonObj.getString("code")
                        if (code == "200") {
                            requestAddCommentCallback.requestAddCommentSucceed()
                        }
                    }
                })
    }

    interface RequestAddCommentCallback {
        fun requestAddCommentSucceed()
    }


    fun requestAddCollection(activity: AppCompatActivity, userId: Int, knowledgeId: Int, requestAddCollectionCallback: RequestAddCollectionCallback) {
        val map = HashMap<String, Any>()
        map["userId"] = userId
        map["knowledgeId"] = knowledgeId
        val jsonObj = JSONObject(map)
        OkGo.post<String>(NetConstant.REQUEST_HEADER + NetApi.API_KNOWLEDGE_ADD_COLLECT)
                .tag(activity)
                .upJson(jsonObj)
                .execute(object : StringCallback() {
                    override fun onSuccess(response: Response<String>?) {
                        val jsonObject = JSONObject(response!!.body())
                        val code = jsonObject.getString("code")
                        if (code == "200") {
                            requestAddCollectionCallback.requestAddCollectionSucceed()
                        }
                    }
                })
    }

    interface RequestAddCollectionCallback {
        fun requestAddCollectionSucceed()
    }

    fun requestUpload(activity: AppCompatActivity, userId: Int, knowledgeType: Int, knowledgeTitle: String, knowledgeDescribe: String, coverImg: File, file: File, knowledgeClassify: ArrayList<Int>, knowledgeContent: String) {

//        if (knowledgeType == 3){
//
//            requestAddDocumentKnowledge(activity,userId,knowledgeType,knowledgeTitle,knowledgeContent)
//
//            return
//        }


        OkGo.post<String>(NetConstant.REQUEST_HEADER + NetApi.API_UPLOAD_FILE)
                .tag(activity)
                .params("file", file)
                .execute(object : StringCallback() {
                    override fun onSuccess(response: Response<String>?) {
                        val jsonObj = JSONObject(response!!.body())
                        val code = jsonObj.getString("code")
                        if (code == "200") {
                            val filePath = jsonObj.getString("data")
                            requestUploadFile2(activity, userId, knowledgeType, knowledgeTitle, knowledgeDescribe, coverImg, file, filePath, knowledgeClassify, knowledgeContent)
                        } else {
                            ToastUtils.showShort("上传文件失败")
                        }
                    }

                    override fun uploadProgress(progress: Progress?) {
                        RxBus.getDefault().post(UploadFileProgressEvent(0x12ff, "文件", (progress!!.fraction * 100).toInt()))
                    }

                    override fun onError(response: Response<String>?) {
                        ToastUtils.showShort("上传文件失败")
                    }
                })
    }

    private fun requestUploadFile2(activity: AppCompatActivity, userId: Int, knowledgeType: Int, knowledgeTitle: String, knowledgeDescribe: String, coverImg: File, file1: File, filePath: String, knowledgeClassify: ArrayList<Int>, knowledgeContent: String) {
        OkGo.post<String>(NetConstant.REQUEST_HEADER + NetApi.API_UPLOAD_FILE)
                .tag(activity)
                .params("file", coverImg)
                .execute(object : StringCallback() {
                    override fun onSuccess(response: Response<String>?) {
                        val jsonObj = JSONObject(response!!.body())
                        val code = jsonObj.getString("code")
                        if (code == "200") {
                            val coverImgPath = jsonObj.getString("data")
                            requestAddKnowledge(activity, userId, knowledgeType, knowledgeTitle, knowledgeDescribe, coverImg, file1, filePath, coverImgPath, knowledgeClassify, knowledgeContent)
                        } else {
                            ToastUtils.showShort("上传封面图片失败！")
                        }
                    }

                    override fun uploadProgress(progress: Progress?) {
                        RxBus.getDefault().post(UploadFileProgressEvent(0x12ff, "图片", (progress!!.fraction * 100).toInt()))
                    }

                    override fun onError(response: Response<String>?) {
                    }
                })
    }

    private fun requestAddKnowledge(activity: AppCompatActivity, userId: Int, knowledgeType: Int, knowledgeTitle: String, knowledgeDescribe: String, coverImg: File, file1: File, filePath: String, coverImgPath: String, knowledgeClassify: ArrayList<Int>, knowledgeContent: String) {
        val map = HashMap<String, Any>()
        map["knowledgeType"] = knowledgeType
        map["knowledgeTitle"] = knowledgeTitle
        map["knowledgeAuthor"] = userId
        map["coverImg"] = coverImgPath
        map["fileAddress"] = filePath
        map["knowledgeDescribe"] = knowledgeDescribe
        map["knowledgeContent"] = knowledgeContent
        if (knowledgeClassify.isNotEmpty()) {
            map["types"] = knowledgeClassify
        }

        val jsonObject = JSONObject(map)
        OkGo.post<String>(NetConstant.REQUEST_HEADER + NetApi.API_ADD_KNOWLEDGE)
                .tag(activity)
                .upJson(jsonObject)
                .execute(object : StringCallback() {
                    override fun onSuccess(response: Response<String>?) {
                        val jsonObject = JSONObject(response!!.body())
                        val code = jsonObject.getString("code")
                        if (code == "200") {
                            ToastUtils.showShort("知识上传成功！")
                            RxBus.getDefault().post(UploadFileSucceedEvent(0x13ff))
                        }
                    }

                    override fun onError(response: Response<String>?) {
                        ToastUtils.showShort("上传知识失败！")
                    }
                })
    }


    fun requestAddDocumentKnowledge(activity: AppCompatActivity, userId: Int, knowledgeType: Int, knowledgeTitle: String, knowledgeDescribe: String, knowledgeClassify: ArrayList<Int>, knowledgeContent: String) {
        val map = HashMap<String, Any>()
        map["knowledgeType"] = knowledgeType
        map["knowledgeTitle"] = knowledgeTitle
        map["knowledgeAuthor"] = userId
        map["knowledgeDescribe"] = knowledgeDescribe
        map["knowledgeContent"] = knowledgeContent
        if (knowledgeClassify.isNotEmpty()) {
            map["types"] = knowledgeClassify
        }
        val jsonObject = JSONObject(map)
        OkGo.post<String>(NetConstant.REQUEST_HEADER + NetApi.API_ADD_KNOWLEDGE)
                .tag(activity)
                .upJson(jsonObject)
                .execute(object : StringCallback() {
                    override fun onSuccess(response: Response<String>?) {
                        val jsonObject = JSONObject(response!!.body())
                        val code = jsonObject.getString("code")
                        if (code == "200") {
                            ToastUtils.showShort("知识上传成功！")
                            RxBus.getDefault().post(UploadFileSucceedEvent(0x13ff))
                        }
                    }

                    override fun onError(response: Response<String>?) {
                        ToastUtils.showShort("上传知识失败！")
                    }
                })
    }


    fun isDownloading(fileName: String): Boolean {
        var isDownload = false

        if (FileUtils.createOrExistsDir(Environment.getExternalStorageDirectory().absolutePath + File.separator + "享学知识缓存文件" + File.separator)) {
            val filesInDir = FileUtils.listFilesInDir(Environment.getExternalStorageDirectory().absolutePath + File.separator + "享学知识缓存文件" + File.separator)
            //获取文件夹路径
            for (file in filesInDir) {
                //文件分组
                if (FileUtils.getFileName(file) == fileName) {
                    isDownload = true
                }
            }
        } else {
            ToastUtils.showLong("文件夹不存在！")
        }
        return isDownload
    }


    fun requestKnowledgeDetail(knowledgeId: Int, requestKnowledgeDetailCallback: RequestKnowledgeDetailCallback) {
        val map = HashMap<String, Any>()
        map["knowledgeId"] = knowledgeId
        map["userId"] = MyApp.instance().userAccount!!.id
        val jsonObject = JSONObject(map)
        OkGo.post<String>(NetConstant.REQUEST_HEADER + NetApi.API_KNOWLEDGE_DETAIL)
                .tag(this)
                .upJson(jsonObject)
                .execute(object : StringCallback() {
                    override fun onSuccess(response: Response<String>?) {
                        val jsonObj = JSONObject(response!!.body())
                        val data = jsonObj.getJSONObject("data")
                        val knowledgeTitle = data.getString("knowledgeTitle")
                        val knowledgeContent = data.getString("knowledgeContent")
                        val author = data.getString("userName")
                        val coverImg = data.getString("coverImg")
                        val createDate = data.getLong("createDate")
                        val browseNum = data.getInt("browseNumber")
                        val isCollect = data.getInt("isCollect")
                        val isPraise = data.getInt("isPraise")
                        val praiseNum = data.getInt("praiseNumber")
                        val fileAddress = data.getString("fileAddress")
                        val knowledgeDescribe = data.getString("knowledgeDescribe")

                        requestKnowledgeDetailCallback.requestKnowledgeDetailsSucceed(knowledgeTitle, knowledgeContent, createDate, browseNum, isCollect, isPraise, praiseNum, coverImg, author, knowledgeDescribe, fileAddress)
                    }
                })
    }

    interface RequestKnowledgeDetailCallback {
        fun requestKnowledgeDetailsSucceed(knowledgeTitle: String, knowledgeContent: String, createDate: Long, browseNum: Int, isCollect: Int, isPraise: Int, praiseNum: Int, coverImg: String, author: String, knowledgeDescribe: String, fileAddress: String)
    }


    fun requestMyInfo(context: Context, userInfoCallback: UserInfoCallback) {
        val map = HashMap<String, Any>()
        map["userId"] = MyApp.instance().userAccount!!.id
        val jsonObject = JSONObject(map)
        OkGo.post<String>(NetConstant.REQUEST_HEADER + NetApi.API_MY_INFO)
                .tag(context)
                .upJson(jsonObject)
                .execute(object : StringCallback() {
                    override fun onSuccess(response: Response<String>?) {
                        val jsonObj = JSONObject(response!!.body())
                        val data = jsonObj.getJSONObject("data")
                        val userId = data.getInt("id")
                        val headImg = data.getString("headImg")
                        userInfoCallback.reqeustUserInfoSucceed(headImg)
                        val userAccount = MyApp.instance().userAccount!!
                        userAccount.headImg = headImg
                        MyApp.instance().putUserAccount(userAccount)
                    }
                })
    }


    interface UserInfoCallback {
        fun reqeustUserInfoSucceed(headImg: String)
    }

    fun requestAddPraise(knowledgeId: Int, addPraiseCallback: AddPraiseCallback) {
        val map = HashMap<String, Int>()
        map["knowledgeId"] = knowledgeId
        map["userId"] = MyApp.instance().userAccount!!.id
        val jsonObj = JSONObject(map)
        OkGo.post<String>(NetConstant.REQUEST_HEADER + NetApi.API_KNOWLEDGE_ADD_PRAISE)
                .tag(this)
                .upJson(jsonObj)
                .execute(object : StringCallback() {
                    override fun onSuccess(response: Response<String>?) {
                        val josnObj = JSONObject(response!!.body())
                        val code = josnObj.getString("code")
                        if (code == "200") {
                            addPraiseCallback.requestAddPraiseSucceed()
                        } else if (code == "503") {
                            ToastUtils.showShort("您已经点赞啦~")
                        }
                    }
                })
    }

    interface AddPraiseCallback {
        fun requestAddPraiseSucceed()
    }


    fun requestAddCommentPraise(commentId: Int, activity: AppCompatActivity, addCommentPraiseCallback: AddCommentPraiseCallback) {
        val map = HashMap<String, Int>()
        map["userId"] = MyApp.instance().userAccount!!.id
        map["commentId"] = commentId
        val upJson = JSONObject(map)
        OkGo.post<String>(NetConstant.REQUEST_HEADER + NetApi.API_COMMENT_PRAISE)
                .tag(activity)
                .upJson(upJson)
                .execute(object : StringCallback() {
                    override fun onSuccess(response: Response<String>?) {
                        val jsonObj = JSONObject(response!!.body())
                        val code = jsonObj.getString("code")
                        if (code == "200") {
                            addCommentPraiseCallback.requestAddCommentPraiseSucceed()
                        } else {
                            addCommentPraiseCallback.requestAddCommentPraiseFailed()
                        }
                    }

                    override fun onError(response: Response<String>?) {
                        super.onError(response)
                        addCommentPraiseCallback.requestAddCommentPraiseFailed()
                    }

                })
    }

    interface AddCommentPraiseCallback {
        fun requestAddCommentPraiseSucceed()
        fun requestAddCommentPraiseFailed()
    }

    fun requestDelMyComment(activity: AppCompatActivity, commentId: Int, delMyCommentCallback: DelMyCommentCallback) {
        val map = HashMap<String, Int>()
        map["commentId"] = commentId
        val upJson = JSONObject(map)
        OkGo.post<String>(NetConstant.REQUEST_HEADER + NetApi.API_DELET_MY_COMMENT)
                .tag(activity)
                .upJson(upJson)
                .execute(object : StringCallback() {
                    override fun onSuccess(response: Response<String>?) {
                        val jsonObj = JSONObject(response!!.body())
                        val code = jsonObj.getString("code")
                        if (code == "200") {
                            delMyCommentCallback.requestDelMyCommentSucceed()
                        } else {
                            delMyCommentCallback.requestDelMyCommentFailed()
                        }
                    }


                    override fun onError(response: Response<String>?) {
                        super.onError(response)
                        delMyCommentCallback.requestDelMyCommentFailed()
                    }
                })
    }

    interface DelMyCommentCallback {
        fun requestDelMyCommentSucceed()
        fun requestDelMyCommentFailed()
    }


    fun requestAddStudyTime(activity: AppCompatActivity, knowledgeId: Any, addStudyTimeCallback: AddStudyTimeCallback) {
        val map = HashMap<String, Any>()
        map["userId"] = MyApp.instance().userAccount!!.id
        map["knowledgeId"] = knowledgeId
        OkGo.post<String>(NetConstant.REQUEST_HEADER + NetApi.API_STUDY_ADD)
                .tag(activity)
                .upJson(JSONObject(map))
                .execute(object :StringCallback(){
                    override fun onSuccess(response: Response<String>?) {
                        val jsonObject = JSONObject(response!!.body())
                        val code = jsonObject.getString("code")
                        if (code == "200"){
                            addStudyTimeCallback.requestAddStudyTimeSucceed()
                        }else{
                            addStudyTimeCallback.requestAddStudyTimeFailed()
                        }
                    }

                    override fun onError(response: Response<String>?) {
                        super.onError(response)
                        addStudyTimeCallback.requestAddStudyTimeFailed()
                    }
                })
    }


    fun requestAddStudyTime(mContext: Context, knowledgeId: Any, addStudyTimeCallback: AddStudyTimeCallback) {
        val map = HashMap<String, Any>()
        map["userId"] = MyApp.instance().userAccount!!.id
        map["knowledgeId"] = knowledgeId
        OkGo.post<String>(NetConstant.REQUEST_HEADER + NetApi.API_STUDY_ADD)
                .tag(mContext)
                .upJson(JSONObject(map))
                .execute(object :StringCallback(){
                    override fun onSuccess(response: Response<String>?) {
                        val jsonObject = JSONObject(response!!.body())
                        val code = jsonObject.getString("code")
                        if (code == "200"){
                            addStudyTimeCallback.requestAddStudyTimeSucceed()
                        }else{
                            addStudyTimeCallback.requestAddStudyTimeFailed()
                        }
                    }

                    override fun onError(response: Response<String>?) {
                        super.onError(response)
                        addStudyTimeCallback.requestAddStudyTimeFailed()
                    }
                })
    }




    interface AddStudyTimeCallback {
        fun requestAddStudyTimeSucceed()
        fun requestAddStudyTimeFailed()
    }
}